var API = (function() {
    const TOKEN_KEY = 'token';

    //注册
    async function reg(userInfo) {

        const resp = await post('api/user/reg', userInfo)
        return await resp.json();
    }

    function get(path) {
        const headers = {}
        const token = localStorage.getItem(TOKEN_KEY)
        if (token) {
            headers.authorization = `bearer ${token}`
        }

        return fetch("https://study.duyiedu.com/" + path, { headers })
    }

    function post(path, obj) {
        const headers = {
            'content-type': 'application/json'
        }
        const token = localStorage.getItem(TOKEN_KEY)
        if (token) {
            headers.authorization = `bearer ${token}`
        }

        return fetch("https://study.duyiedu.com/" + path, { headers, method: 'POST', body: JSON.stringify(obj) })
    }
    //登陆
    async function login(loginInfo) {
        const resp = await post('api/user/login', loginInfo)
        const result = await resp.json();
        if (result.code === 0) {
            const token = resp.headers.get('authorization')
            localStorage.setItem('token', token)
        }
        return result;
    }
    //验证账号
    async function exists(loginId) {
        const resp = await get('api/user/exists?loginId=' + loginId)
        return await resp.json();
    }
    //查询当前用户信息
    async function profile() {
        const resp = await get('api/user/profile')
        return await resp.json();
    }
    //聊天函数
    async function sendChat(content) {
        const resp = await post('api/chat', { content })
        return await resp.json();
    }
    //聊天记录
    async function getHistory() {
        const resp = await get('api/chat/history')
        return await resp.json();
    }

    function removelLogin() {
        localStorage.removeItem(TOKEN_KEY);
    }
    return {
        reg,
        login,
        exists,
        removelLogin,
        getHistory,
        sendChat,
        profile
    }
})()